﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.CarManage;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class CarManagement : Form
    {
        private List<CarData> carList = new List<CarData>();
        private CCWin.SkinControl.SkinDataGridView dgvCarInfo;
        
        public CarManagement()
        {
            InitializeComponent();
            InitializeForm();
        }
        
        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitializeForm()
        {
            try
            {
                // 设置窗体标题
                this.Text = "车间管理";
                
                // 绑定提交按钮事件
                if (btnCarAdd != null)
                {
                    btnCarAdd.Click += BtnCarAdd_Click;
                }
                
                // 绑定选择负责人按钮事件
                if (btnLeader != null)
                {
                    btnLeader.Click += BtnLeader_Click;
                }
                
                // 初始化车间信息页面
                InitializeCarInfoPage();
                
                // 加载车间数据
                LoadCarData();
                
                Console.WriteLine("车间管理窗体初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化窗体时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 初始化车间信息页面
        /// </summary>
        private void InitializeCarInfoPage()
        {
            try
            {
                // 检查车间信息页面是否存在
                if (tabCarInfo == null)
                {
                    MessageBox.Show("车间信息页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 创建车间信息DataGridView控件
                var dgvCarInfo = new CCWin.SkinControl.SkinDataGridView();
                dgvCarInfo.Name = "dgvCarInfo";
                dgvCarInfo.Dock = DockStyle.Fill;
                dgvCarInfo.Location = new Point(0, 0);
                dgvCarInfo.Size = new Size(tabCarInfo.Width, tabCarInfo.Height);
                
                // 设置DataGridView的基本属性
                dgvCarInfo.AutoGenerateColumns = false;
                dgvCarInfo.AllowUserToAddRows = false;
                dgvCarInfo.AllowUserToDeleteRows = false;
                dgvCarInfo.ReadOnly = true;
                dgvCarInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvCarInfo.MultiSelect = false;
                dgvCarInfo.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                
                // 添加列定义
                // 车间编号列
                DataGridViewTextBoxColumn colCarCode = new DataGridViewTextBoxColumn();
                colCarCode.HeaderText = "车间编号";
                colCarCode.DataPropertyName = "CarCode";
                colCarCode.Width = 90;
                dgvCarInfo.Columns.Add(colCarCode);
                
                // 车间名称列
                DataGridViewTextBoxColumn colCarName = new DataGridViewTextBoxColumn();
                colCarName.HeaderText = "车间名称";
                colCarName.DataPropertyName = "CarName";
                colCarName.Width = 100;
                dgvCarInfo.Columns.Add(colCarName);
                
                // 车间面积列
                DataGridViewTextBoxColumn colCarArea = new DataGridViewTextBoxColumn();
                colCarArea.HeaderText = "车间面积";
                colCarArea.DataPropertyName = "CarArea";
                colCarArea.Width = 100;
                dgvCarInfo.Columns.Add(colCarArea);
                
                // 负责人列
                DataGridViewTextBoxColumn colLeader = new DataGridViewTextBoxColumn();
                colLeader.HeaderText = "负责人";
                colLeader.DataPropertyName = "Leader";
                colLeader.Width = 100;
                dgvCarInfo.Columns.Add(colLeader);
                
                // 设置CSkin DataGridView样式
                dgvCarInfo.BackgroundColor = Color.White;
                dgvCarInfo.BorderStyle = BorderStyle.None;
                dgvCarInfo.GridColor = Color.LightGray;
                dgvCarInfo.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
                dgvCarInfo.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
                dgvCarInfo.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                dgvCarInfo.RowHeadersVisible = false;
                
                // 将DataGridView添加到车间信息页面
                tabCarInfo.Controls.Add(dgvCarInfo);
                
                // 保存控件引用
                this.dgvCarInfo = dgvCarInfo;
                
                Console.WriteLine("车间信息页面初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化车间信息页面时出错: {ex.Message}");
                MessageBox.Show($"初始化车间信息页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载车间数据
        /// </summary>
        private async void LoadCarData()
        {
            try
            {
                Console.WriteLine("=== 开始加载车间数据 ===");
                
                // 检查dgvCarInfo控件是否存在
                if (dgvCarInfo == null)
                {
                    MessageBox.Show("车间信息 DataGridView控件未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 显示加载状态
                dgvCarInfo.DataSource = null;
                
                // 调用车间信息 API
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    Console.WriteLine("正在调用车间信息API...");
                    var response = await client.GetAsync("http://localhost:5281/api/Car/GetCar");
                    response.EnsureSuccessStatusCode();
                    
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"车间信息API响应: {jsonResponse}");
                    
                    var apiResponse = JsonConvert.DeserializeObject<ApiCarInfoResponse>(jsonResponse);
                    
                    if (apiResponse?.code == 200 && apiResponse.data != null)
                    {
                        Console.WriteLine($"车间信息API调用成功，数据条数: {apiResponse.data.Count}");
                        
                        // 设置车间数据到DataGridView
                        carList = apiResponse.data;
                        dgvCarInfo.DataSource = carList;
                        
                        // 调整列宽
                        dgvCarInfo.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                        
                        Console.WriteLine($"成功加载 {carList.Count} 个车间数据");
                        Console.WriteLine("=== 车间数据加载完成 ===");
                    }
                    else
                    {
                        Console.WriteLine($"车间信息API调用失败: code={apiResponse?.code}, msg={apiResponse?.msg}");
                        MessageBox.Show($"车间数据加载失败: {apiResponse?.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"HTTP请求错误: {ex.Message}");
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON解析错误: {ex.Message}");
                MessageBox.Show($"数据解析失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载车间数据时出错: {ex.Message}");
                MessageBox.Show($"加载车间数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 提交按钮点击事件
        /// </summary>
        private async void BtnCarAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("=== 开始提交车间信息 ===");
                
                // 验证输入数据
                if (!ValidateInput())
                {
                    return;
                }
                
                // 构建车间数据
                var carData = BuildCarData();
                
                // 调用API添加车间
                bool success = await AddCarAsync(carData);
                
                if (success)
                {
                    MessageBox.Show("车间信息添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    
                    // 刷新车间信息列表
                    LoadCarData();
                }
                
                Console.WriteLine("=== 提交车间信息完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"提交车间信息时出错: {ex.Message}");
                MessageBox.Show($"提交车间信息时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 选择负责人按钮点击事件
        /// </summary>
        private void BtnLeader_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开选择用户窗体
                using (var selectUsersForm = new SelectUsers())
                {
                    if (selectUsersForm.ShowDialog() == DialogResult.OK)
                    {
                        // 获取选中的用户信息
                        var selectedUser = selectUsersForm.SelectedUser;
                        if (selectedUser != null)
                        {
                            txtCarLeader.Text = selectedUser.userName;
                            Console.WriteLine($"已选择负责人: {selectedUser.userName} (部门: {selectedUser.departmentName})");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择负责人时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 验证输入数据
        /// </summary>
        private bool ValidateInput()
        {
            // 验证车间编号
            if (string.IsNullOrWhiteSpace(txtCarCode.Text))
            {
                MessageBox.Show("请输入车间编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarCode.Focus();
                return false;
            }
            
            // 验证车间名称
            if (string.IsNullOrWhiteSpace(txtCarName.Text))
            {
                MessageBox.Show("请输入车间名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarName.Focus();
                return false;
            }
            
            // 验证车间面积
            if (string.IsNullOrWhiteSpace(txtCarArea.Text))
            {
                MessageBox.Show("请输入车间面积", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarArea.Focus();
                return false;
            }
            
            // 验证负责人
            if (string.IsNullOrWhiteSpace(txtCarLeader.Text))
            {
                MessageBox.Show("请选择负责人", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarLeader.Focus();
                return false;
            }
            
            return true;
        }
        
        /// <summary>
        /// 构建车间数据
        /// </summary>
        private CarData BuildCarData()
        {
            return new CarData
            {
                CarCode = txtCarCode.Text.Trim(),
                CarName = txtCarName.Text.Trim(),
                CarArea = txtCarArea.Text.Trim(),
                Leader = txtCarLeader.Text.Trim()
            };
        }
        
        /// <summary>
        /// 调用API添加车间
        /// </summary>
        private async Task<bool> AddCarAsync(CarData carData)
        {
            try
            {
                Console.WriteLine("正在调用添加车间API...");
                
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 构建请求数据
                    var requestData = new
                    {
                        carCode = carData.CarCode,
                        carName = carData.CarName,
                        carArea = carData.CarArea,
                        leader = carData.Leader
                    };
                    
                    // 序列化为JSON
                    string jsonData = JsonConvert.SerializeObject(requestData);
                    Console.WriteLine($"请求数据: {jsonData}");
                    
                    // 创建HTTP内容
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    var response = await client.PostAsync("http://localhost:5281/api/Car/AddCar", content);
                    response.EnsureSuccessStatusCode();
                    
                    // 读取响应
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应: {jsonResponse}");
                    
                    // 反序列化响应
                    var apiResponse = JsonConvert.DeserializeObject<ApiCarResponse>(jsonResponse);
                    
                    if (apiResponse?.code == 200)
                    {
                        Console.WriteLine($"车间添加成功，影响行数: {apiResponse.data}");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine($"车间添加失败: code={apiResponse?.code}, msg={apiResponse?.msg}");
                        MessageBox.Show($"车间添加失败: {apiResponse?.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"HTTP请求错误: {ex.Message}");
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON解析错误: {ex.Message}");
                MessageBox.Show($"数据解析失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加车间时出错: {ex.Message}");
                MessageBox.Show($"添加车间时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        
        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            try
            {
                txtCarCode.Text = "";
                txtCarName.Text = "";
                txtCarArea.Text = "";
                txtCarLeader.Text = "";
                
                // 将焦点设置到车间编号输入框
                txtCarCode.Focus();
                
                Console.WriteLine("表单已清空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空表单时出错: {ex.Message}");
            }
        }

        private void tabCarInfo_Click(object sender, EventArgs e)
        {

        }
    }
}
